using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.Operations.Commands;

/// <summary>
/// 工序更新命令。
/// </summary>
public record UpdateOperationCommand(long Id, ProcOperationDto Operation) : IRequest<IResult<bool>>;

internal sealed class UpdateOperationCommandHandler(IRepository<ProcOperation> repo) : IRequestHandler<UpdateOperationCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateOperationCommand request, CancellationToken cancellationToken)
    {
        var operation = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (operation == null)
        {
            return Result.Failure("未找到要更新的工序");
        }

        operation.OpName = request.Operation.OpName;
        operation.LineId = request.Operation.LineId;
        operation.WsIds = request.Operation.WsIds;
        operation.ProcessCategory = request.Operation.ProcessCategory;
        operation.ProcessTypeCode = request.Operation.ProcessTypeCode;
        operation.ProcessTypeName = request.Operation.ProcessTypeName;
        operation.Order = request.Operation.Order;
        operation.Status = request.Operation.Status;
        operation.Tag = request.Operation.Tag;

        var ok = await repo.UpdateAsync(operation, m => new
        {
            m.OpName,
            m.LineId,
            m.WsIds,
            m.ProcessCategory,
            m.ProcessTypeCode,
            m.ProcessTypeName,
            m.Order,
            m.Status,
            m.Tag,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
